package com.mayuhao.time.service;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author YHwinner
 */
public class Service {
    public static void main(String[] args) {
        new Service();
    }

    public Service() {

        try {
            System.out.println("****服务端已启用****");
            ServerSocket serverSocket = new ServerSocket(6666);

            while (true) {

                //监听多线程客户端
                Socket socket = serverSocket.accept();

                //开启线程
                ExecutorService executorService = Executors.newFixedThreadPool(1);
                executorService.execute(new ThreadService(socket));
                executorService.shutdown();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    class ThreadService implements Runnable {
        private Socket socket;

        public ThreadService(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {

            try {
                while (true) {
                    DataInputStream is = new DataInputStream(socket.getInputStream());
                    String s = is.readUTF();
                    String format = new SimpleDateFormat("yyyy 年 MM 月 dd 日  EEEE HH:mm:ss ").format(new Date());
                    if (s.equals("GO")) {
                        //将消息发送到客户端
                        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                        dos.writeUTF(format);
                        System.out.println(format);
                        dos.flush();

                    } else {
                        System.out.println("数据为空，无法返回时间！！！");
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}
